<?php
namespace app\agent\logic;

use app\common\model\WkOrderModel;

class WkOrderLogic extends WkOrderModel
{
	
	public function getPage($where = [], $request = [])
	{
        $where[] = ['frompay', 'neq', 3];

		//排序
		$order = [
				'status' => 'DESC',
				$this->getPk() => 'DESC',
		];

		//查询数据
		$data = $this->where($where)->order($order)->paginate(10, false, ['query' => $request]);

		//字段属性映射
		foreach ($data as $key => &$val)
		{
			$this->attributeMap($val);
		}
		
		return $data;
	}

	public function updateRecord($data = [])
	{
		//入库
		$data = $this->allowField(true)->save($data, [$this->getPk() => $data['id']]);
		
		if( $data === false )
		{
			return false;
		}
		
		return true;
	}
	
	public function destroyRecord($id = 0)
	{
		return $this->delete($id);
	}

	public function getDetail($where = [])
	{
		//查询数据
		$data = $this->where($where)->find();

		//字段属性映射
		$data = $this->attributeMap($data);

		return $data;
	}

    public function getOrderCount($where = [])
    {
        return $this->where($where)->count(1);
	}

    /**
     * @action 根据时间获取代理区域的收益 (该方法有很大优化空间)
     */
    public function getAgentProfit($where = [])
    {
        $field = [
            'sum(total_fee) fee',
        ];

        $join = [
            ['wk_sellerinfo info', 'info.uid = order.suid'],
        ];

        $where[] = ['order.status', '>', 0];

        //线下收益
        $where_offline   = $where;
        $where_offline[] = ['order.ordertype', '=', 1];
        $where_offline[] = ['order.payType', '<>', 3];

        $profit['offline'] = $this->alias('order')->field($field)->join($join)->where($where_offline)->find();


        //线上收益
        $where_online   = $where;
        $where_online[] = ['order.ordertype', '=', 2];

        $where_or   = $where;
        $where_or[] = ['order.ordertype', '=', 1];
        $where_or[] = ['order.payType', '=', 3];

        $profit['online'] = $this->alias('order')->field($field)->join($join)->whereOr([$where_online, $where_or])->find();

        return $profit;
	}
}